package wifiunion.com.notice.widget;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.RelativeLayout;
import android.widget.TextView;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import wifiunion.com.notice.BasePresenter;
import wifiunion.com.notice.CommonUtils;
import wifiunion.com.notice.Constants;
import wifiunion.com.notice.MyNoticeListener;
import wifiunion.com.notice.NoticeContact;
import wifiunion.com.notice.R;
import wifiunion.com.notice.RecyclerItemClick;
import wifiunion.com.notice.adapter.AdRelGroupDeviceAdapter;
import wifiunion.com.notice.adapter.DeviceSelectSthAdapter;
import wifiunion.com.notice.entity.DeviceInList;
import wifiunion.com.notice.entity.DeviceLocation;
import wifiunion.com.notice.entity.DeviceRlGroupDetail;
import wifiunion.com.notice.entity.DeviceSelectSth;
import wifiunion.com.notice.entity.NoticeDeviceRlGroup;
import wifiunion.com.notice.entity.NotificationRequest;
import wifiunion.com.notice.presenter.NoticeAddRelDeviceGroupPresenter;
import wifiunion.com.notice.presenter.NoticeRelDeviceGroupListPresenter;
import wifiunion.com.notice.presenter.NoticeRelDeviceGroupUuidPresenter;
import wifiunion.com.notice.utils.SharedPreferencesUtils;


/**
 * 通知设备添加
 */

public class AddNoticeGroupDeviceDialog extends Dialog implements ExpandableListView.OnGroupClickListener, NoticeContact.View, ExpandableListView.OnGroupExpandListener, View.OnClickListener, RecyclerItemClick {
    private Context context;
    private TextView titleName;
    private int pageNum = 1;
    private int pageSize = 5000;

    private ExpandableListView mExpandlistView;
    private AdRelGroupDeviceAdapter mAdapter;

    private ArrayList<NoticeDeviceRlGroup> mList = new ArrayList<NoticeDeviceRlGroup>();

    private TextView cancelTxt;
    private TextView confirmTxt;
    private TextView loccancelTxt, locconfirmTxt;

//    private Spinner mDeviceLocSpinner;

    private EditText mDeviceNoEdt;

    private Button mSearchBtn;

    private NoticeRelDeviceGroupListPresenter mRelGroupPresenter;

    private NoticeRelDeviceGroupUuidPresenter mNoticeRelDeviceGroupUuidPresenter;

    private NoticeAddRelDeviceGroupPresenter mNoticeAddRelDeviceGroupPresenter;


    /**
     * 全部设备列表
     */
    private List<DeviceInList> mAllDeviceList = new ArrayList<>();



    private NoticeDeviceRlGroup currentGroup;


    private String noticeUuid;

    private RelativeLayout mGroupRl, mLocationRl;

    private ArrayList<DeviceLocation> mLocSpinnerlist = new ArrayList<>();
    public MyNoticeListener myListener;
    public DeviceLocation mChooseDeviceLocationl;//选重的位置
    private String authtoken;
    private TextView mLocationTv;

    private DeviceSelectSthAdapter mLocationAdapter;
    /**
     * 设备位置的列表
     */
    private ArrayList<DeviceSelectSth> mSelectSthLocList = new ArrayList<DeviceSelectSth>();

    private RecyclerView mLocationListView;

    /**
     * 选中设备的在列表中的位置
     */
    private int mLocationSelectPos = 0;


    //无条件查询 false 无条件 true 有条件查询
    private boolean unconditional;

    /**
     * 0 通知
     * 1 在岗巡查
     * 2 曝光
     */
    private int mType;


    public AddNoticeGroupDeviceDialog(Context context, Activity activity, String uuid, ArrayList<DeviceLocation> mLocSpinnerlist, MyNoticeListener myListener, int type) {
        super(context, R.style.alert_dialog);
        noticeUuid = uuid;
        this.context = context;
        this.mLocSpinnerlist = mLocSpinnerlist;
        this.myListener = myListener;
        this.mType = type;
        authtoken = SharedPreferencesUtils.getSharedPreferences(
                Constants.CONFIG_AUTHTOKEN, getContext());
        LayoutInflater li = LayoutInflater.from(context);
        ViewGroup contentView = (ViewGroup) li.inflate(
                R.layout.dialog_add_devicegroup, null);
        contentView.bringToFront();
        mRelGroupPresenter = new NoticeRelDeviceGroupListPresenter(getContext(), this);
        mNoticeRelDeviceGroupUuidPresenter = new NoticeRelDeviceGroupUuidPresenter(getContext(), this);
        mNoticeAddRelDeviceGroupPresenter = new NoticeAddRelDeviceGroupPresenter(getContext(), this);
        cancelTxt = (TextView) contentView.findViewById(R.id.cancel_txt);
        confirmTxt = (TextView) contentView.findViewById(R.id.confirm_txt);
        titleName = (TextView) contentView.findViewById(R.id.tv_title_name);
        mLocationTv = (TextView) contentView.findViewById(R.id.device_deviceloc_tv);
        mGroupRl = (RelativeLayout) contentView.findViewById(R.id.ll_content);
        mLocationRl = (RelativeLayout) contentView.findViewById(R.id.location_content);
        cancelTxt = (TextView) contentView.findViewById(R.id.cancel_txt);

        loccancelTxt = (TextView) contentView.findViewById(R.id.cancel1_txt);
        locconfirmTxt = (TextView) contentView.findViewById(R.id.confirm1_txt);

        mDeviceNoEdt = (EditText) contentView.findViewById(R.id.device_deviceloc_search_edt);
        mSearchBtn = (Button) contentView.findViewById(R.id.device_deviceloc_search_btn);

        mLocationListView = (RecyclerView) contentView.findViewById(R.id.locationlist);
        mExpandlistView = (ExpandableListView) contentView.findViewById(R.id.elist);
        mExpandlistView.setGroupIndicator(null);
        if (null != mLocSpinnerlist && mLocSpinnerlist.size() > 0) {
            mChooseDeviceLocationl = mLocSpinnerlist.get(0);
            mLocationTv.setText(mChooseDeviceLocationl.getName());
        }


        mAdapter = new AdRelGroupDeviceAdapter(getContext(), mList, itemClickListener);
        mExpandlistView.setAdapter(mAdapter);
        mExpandlistView.setOnGroupClickListener(this);
//        只打开一个分组
        mExpandlistView.setOnGroupExpandListener(this);
        getNoticeRelGroupList();
        cancelTxt.setOnClickListener(this);
        confirmTxt.setOnClickListener(this);
        loccancelTxt.setOnClickListener(this);
        locconfirmTxt.setOnClickListener(this);
        mSearchBtn.setOnClickListener(this);
//        setCancelListener();
//        setComfirmListener();
        mLocationTv.setOnClickListener(this);
        setCanceledOnTouchOutside(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;
        onWindowAttributesChanged(lp);
        setContentView(contentView);


    }

    /**
     * 获取已被关联的分组列表
     */
    public void getNoticeRelGroupList() {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("Authorization", authtoken);
        params.put("uuid", noticeUuid);
        if (!TextUtils.isEmpty(mDeviceNoEdt.getText().toString())) {
            params.put("condition", mDeviceNoEdt.getText().toString());
        } else {
//            params.put("condition", "");

        }
        if (!"-1".equals(mChooseDeviceLocationl.getUuid())) {
            params.put("deviceLocationUuid", mChooseDeviceLocationl.getUuid());
        }
        mRelGroupPresenter.setType(mType);
        mRelGroupPresenter.start(params);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = getContext().getResources().getDimensionPixelSize(
                R.dimen.dp_480);
        lp.gravity = Gravity.CENTER;
        lp.height = (int) (CommonUtils.getScreenHeight(getContext()) * 0.9f);
        getWindow().setAttributes(lp);
    }

    public void setTitleMsg(String msg) {
        if (titleName != null) {
            titleName.setText(msg);
        }
    }

    public void setCancleText(String text) {
        if (text != null) {
            cancelTxt.setText(text);
        }
    }


    @Override
    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {

        boolean expanded = parent.isGroupExpanded(groupPosition);
        currentGroup = mList.get(groupPosition);
        if (!expanded) {
            if (!currentGroup.getChilddata().isEmpty()) {
                mExpandlistView.expandGroup(groupPosition);
            } else {
                getChildDataByUuid(currentGroup.getUuid());

            }
            return true;
        }
        return false;
    }


    private View.OnClickListener itemClickListener = new View.OnClickListener() {


        @Override
        public void onClick(View v) {
            int i = v.getId();
            if (i == R.id.device_addgroup_subitem_rl || i == R.id.child_selectall_cb) {
                String tag = (String) v.getTag();
                String[] index = tag.split("-");


                if (mList.get(Integer.parseInt(index[0])).getChilddata().get(Integer.parseInt(index[1])).getIsSelected() == 0) {
                    mList.get(Integer.parseInt(index[0])).getChilddata().get(Integer.parseInt(index[1])).setIsSelected(1);
                } else {
                    mList.get(Integer.parseInt(index[0])).getChilddata().get(Integer.parseInt(index[1])).setIsSelected(0);
                }

                int size = 0;
                for (DeviceRlGroupDetail dgd : mList.get(Integer.parseInt(index[0])).getChilddata()) {
                    if (dgd.getIsSelected() == 0) {
                    } else {
                        size += 1;
                    }

                }

                if (size == mList.get(Integer.parseInt(index[0])).getChilddata().size()) {
                    mList.get(Integer.parseInt(index[0])).setIsSelected(1);
                } else {
                    mList.get(Integer.parseInt(index[0])).setIsSelected(0);

                }
                mAdapter.notifyDataSetChanged();


            } else if (i == R.id.parent_selectall_cb) {
                int groupIndex = (int) v.getTag();

                if (mList.get(groupIndex).getIsSelected() == 0) {
                    mList.get(groupIndex).setIsSelected(1);
                    for (DeviceRlGroupDetail dgd : mList.get(groupIndex).getChilddata()) {

                        dgd.setIsSelected(1);
                    }


                } else {
                    mList.get(groupIndex).setIsSelected(0);
                    for (DeviceRlGroupDetail dgd : mList.get(groupIndex).getChilddata()) {
                        dgd.setIsSelected(0);
                    }
                }

                mAdapter.notifyDataSetChanged();

            }
        }


    };


    @Override
    public void onProgress() {

    }

    @Override
    public void onError(Object obj) {

    }

    @Override
    public void onSuccess(final Object obj) {

    }

    @Override
    public void getGroupListSuccess(Object obj) {

    }

    @Override
    public void getNoticeListSuccess(Object obj) {

    }

    @Override
    public void getNotificationUserSuccess(Object obj) {

    }

    @Override
    public void getNotificationRelGroupList(Object obj) {

    }

    @Override
    public void getNoticeRelGroupMemberListSuccess(Object obj) {

    }

    @Override
    public void addNoticeSBDXSuccess(String noticeUuid) {

    }

    @Override
    public void addSBSDSuccess(Object obj) {

    }


    @Override
    public void onGetDeviceLocListSuccess(final Object obj) {

        currentGroup.getChilddata().addAll((List<DeviceRlGroupDetail>) obj);
//                        setChilddata((List<DeviceRlGroupDetail>) obj);

        mAdapter.notifyDataSetInvalidated();

        mExpandlistView.expandGroup(mList.indexOf(currentGroup));
//                mExpandlistView.expandGroup()
    }

    @Override
    public void onGetDeviceListSuccess(Object obj) {

    }


    @Override
    public void onGetNoticeDeviceGroupListSuccess(final Object obj) {

        mList.addAll((List<NoticeDeviceRlGroup>) obj);

        mAdapter.notifyDataSetChanged();


    }

    @Override
    public void onGetNoticeDeviceGroupUuidSuccess(final Object obj) {

        ArrayList<DeviceRlGroupDetail> mResult = (ArrayList<DeviceRlGroupDetail>) obj;

        if (mResult == null) {
            return;
        } else {
            currentGroup.setChilddata(mResult);

        }
        mAdapter.notifyDataSetChanged();


    }

    @Override
    public void addNoticeDeviceSuccess(Object obj) {

        myListener.refreshData(noticeUuid);
    }

    @Override
    public void getTopGroupListSuccess(Object obj) {

    }

    @Override
    public void getNoticeTargetListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeTargetRelGroupListSuccess(Object obj) {

    }

    @Override
    public void onGetNoticeTargetGroupUuidSuccess(Object obj) {

    }

    @Override
    public void addNoticeTarGetDeviceSuccess(Object obj) {

    }

    @Override
    public void addNoticeDataSuccess(Object obj) {

    }

    @Override
    public void deleteNoticeSuccess(Object obj) {

    }

    @Override
    public void addNoticeGroupSuccess(Object obj) {

    }

    @Override
    public void addNoticeRelGroupSuccess(Object obj) {

    }

    @Override
    public void setNoticeFromSuccess(Object obj) {

    }

    @Override
    public void getNoticeDetailSuccess(Object obj) {

    }

    @Override
    public void deleteNoticeGroupSuccess(Object obj) {

    }


    @Override
    public void setPresenter(BasePresenter tp) {

    }

    private void getChildDataByUuid(String groupUuid) {
        HashMap<String, Object> params = new HashMap<>();

        params.put("Authorization", authtoken);
        params.put("pageNum", String.valueOf(pageNum));
        params.put("pageSize", String.valueOf(pageSize));
        params.put("uuid", noticeUuid);
//        params.put("deviceLocationUuid", "");
        params.put("groupUuid", groupUuid);
        if (!TextUtils.isEmpty(mDeviceNoEdt.getText().toString())) {
            params.put("condition", mDeviceNoEdt.getText().toString());
        } else {
//            params.put("condition", "");
        }
        mNoticeRelDeviceGroupUuidPresenter.setType(mType);
        mNoticeRelDeviceGroupUuidPresenter.getNoticeRelGroupUuid(params);
    }

    @Override
    public void onGroupExpand(int groupPosition) {
        for (int i = 0; i < mAdapter.getGroupCount(); i++) {
            if (i != groupPosition
                    && mExpandlistView.isGroupExpanded(groupPosition)) {
                mExpandlistView.collapseGroup(i);
            } else {
                if (mList.get(groupPosition).getChilddata().isEmpty()) {

                } else {
                    if (mList.get(groupPosition).getIsSelected() == 1) {
                        for (DeviceRlGroupDetail dgd : mList.get(groupPosition).getChilddata()) {
                            dgd.setIsSelected(1);
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }
        }
    }


    private void addDeviceListRequest() {

        HashMap<String, Object> params = new HashMap<>();
        params.put("Authorization", authtoken);
        params.put("uuid", noticeUuid);
        List<NotificationRequest> data = new ArrayList<NotificationRequest>();

        if (unconditional) {


            for (NoticeDeviceRlGroup drg : mList) {
                if (drg.getIsSelected() == 1) {
                    //有条件查询 父级别选中时 父不传只传子级别
                    if (null != drg.getChilddata() && drg.getChilddata().size() > 0) {

                        for (DeviceRlGroupDetail drgd : drg.getChilddata()) {//分组没有全选，设备被选中
                            if (drgd.getIsSelected() == 1) {
                                NotificationRequest submr = new NotificationRequest();
                                if ("0".equals(drgd.getUuid())) {
                                    submr.setIsGroup(1);
                                } else {
                                    submr.setIsGroup(0);
                                }


                                submr.setFromUuid(drgd.getUuid());
                                data.add(submr);
                            }
                        }
                    }


                } else {

                    //有条件查询 父级别未选中时 只传子级别

                    if (null != drg.getChilddata() && drg.getChilddata().size() > 0) {
                        for (DeviceRlGroupDetail drgd : drg.getChilddata()) {//分组没有全选，设备被选中
                            if (drgd.getIsSelected() == 1) {
                                NotificationRequest submr = new NotificationRequest();
                                submr.setIsGroup(0);
                                submr.setFromUuid(drgd.getUuid());
                                data.add(submr);
                            }
                        }
                    }
                }
            }
            if (null != data && data.size() > 0) {
                params.put("data", data);
            }

        } else {
            //无条件查询 父选中只传父级（对应的子级不传）
            for (NoticeDeviceRlGroup drg : mList) {
                if (drg.getIsSelected() == 1) {
                    //分组被选中
                    NotificationRequest mr = new NotificationRequest();
                    mr.setIsGroup(1);
                    mr.setFromUuid(drg.getUuid());
                    data.add(mr);
                    continue;
                } else {
                    if (null != drg.getChilddata() && drg.getChilddata().size() > 0) {
                        for (DeviceRlGroupDetail drgd : drg.getChilddata()) {//分组没有全选，设备被选中
                            if (drgd.getIsSelected() == 1) {
                                NotificationRequest submr = new NotificationRequest();
                                submr.setIsGroup(0);
                                submr.setFromUuid(drgd.getUuid());
                                data.add(submr);
                            }
                        }
                    }
                }
            }
            if (null != data && data.size() > 0) {
                params.put("data", data);
            }
        }
        if (mType == 1) {

            List<Object> r = new ArrayList<Object>();
            for (NoticeDeviceRlGroup drg : mList) {
                for (DeviceRlGroupDetail drgd : drg.getChilddata()) {
                    if (drgd.getIsSelected() == 1) {

                        r.add(drgd);
                    }
                }
            }
            myListener.onResponse(r);
            dismiss();
        } else {
            mNoticeAddRelDeviceGroupPresenter.setType(mType);
            mNoticeAddRelDeviceGroupPresenter.addNoticeDevice(params);
        }
    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.device_deviceloc_tv) {
            mLocationRl.setVisibility(View.VISIBLE);

            mSelectSthLocList.clear();
            for (DeviceLocation deviceLocation : mLocSpinnerlist) {
                DeviceSelectSth dd = new DeviceSelectSth();
                if (mChooseDeviceLocationl.getUuid().equals(deviceLocation.getUuid())) {
                    dd.setSelected(true);
                } else {
                    dd.setSelected(false);
                }
                dd.setName(deviceLocation.getName());
                mSelectSthLocList.add(dd);
            }

            mLocationAdapter = new DeviceSelectSthAdapter(getContext(), mSelectSthLocList, AddNoticeGroupDeviceDialog.this);
            mLocationListView.setLayoutManager(new LinearLayoutManager(context));
            mLocationListView.setAdapter(mLocationAdapter);

        } else if (i == R.id.cancel_txt) {
            dismiss();


        } else if (i == R.id.confirm_txt) {
            addDeviceListRequest();


        } else if (i == R.id.confirm1_txt) {
            if (mLocationSelectPos >= 0) {

                mChooseDeviceLocationl = mLocSpinnerlist.get(mLocationSelectPos);

                try {
                    mLocationTv.setText(mChooseDeviceLocationl.getName());
                    mLocationRl.setVisibility(View.GONE);
                } catch (Exception e) {
                    mChooseDeviceLocationl = mLocSpinnerlist.get(0);
                    mLocationTv.setText(mLocSpinnerlist.get(0).getName());
                    mLocationRl.setVisibility(View.GONE);
                }

            }

        } else if (i == R.id.cancel1_txt) {
            if (mLocationRl.getVisibility() == View.GONE) {
                dismiss();
            } else {
                mLocationRl.setVisibility(View.GONE);
            }

        } else if (i == R.id.device_deviceloc_search_btn) {
            if (!"-1".equals(mChooseDeviceLocationl.getUuid()) || !TextUtils.isEmpty(mDeviceNoEdt.getText().toString())) {
                unconditional = true;
            } else {
                unconditional = false;
            }

            mList.clear();
            getNoticeRelGroupList();


        }


    }

    @Override
    public void onItemClick(View view, int postion) {

        for (int i = 0; i < mSelectSthLocList.size(); i++) {
            if (postion == i) {
                mSelectSthLocList.get(i).setSelected(true);
                mLocationSelectPos = i;
            } else {
                mSelectSthLocList.get(i).setSelected(false);
            }
        }
        mLocationAdapter.notifyDataSetChanged();

    }


//    /**
//     * 把所有DeviceInList都转成DeviceRlGroupDetail类型的
//     *
//     * @param originData
//     */
//    private void transList(ArrayList<DeviceInList> originData) {
//
//        for (NoticeDeviceRlGroup drg : mList) {
//            for (DeviceInList dil : originData) {
//                try {
//                    String[] uuidarray = dil.getGroupUuid().split(";");
//
////                    Log.e(Constants.TAG,"getGroupUuid    "+dil.getGroupUuid());
////                    Log.e(Constants.TAG,"drg.getUuid()    "+drg.getUuid());
////                    Log.e(Constants.TAG,"uuidarray==null   "+(uuidarray==null));
//
//                    List<String> uuidstringlist = Arrays.asList(uuidarray);
//                    if (uuidstringlist.contains(drg.getUuid()) || drg.getUuid().equals("-1")) {
//                        DeviceRlGroupDetail drgd = new DeviceRlGroupDetail();
////                        if (dil.getGroupUuid().contains(mCurrentuuid)) {
////                            drgd.setIsSelected(1);
////                        } else {
////                            drgd.setIsSelected(0);
////                        }
//                        drgd.setDeviceUnique(dil.getDeviceUnique());
//                        drgd.setLocationName(dil.getLocationName());
//                        drgd.setUuid(dil.getUuid());
//                        drg.getChilddata().add(drgd);
//                    }
//                } catch (Exception e) {
////                    Log.e(Constants.TAG,"xxxxxxxxxxxxxxxxxxxxx"+e.getMessage());
//                    continue;
//                }
//
//            }
//        }
//
//
//    }


}